package com.education.platform.api.controller.common;


import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.*;
import com.education.platform.api.service.common.CacheDataService;
import com.education.platform.api.vo.common.CollectionUpdateVO;
import com.education.platform.api.vo.common.LikeUpdateVO;
import com.education.platform.api.vo.request.*;
import com.education.platform.api.vo.response.*;
import com.education.platform.common.enums.AuditTypeEnum;
import com.education.platform.common.enums.RedisCountTypeEnum;
import com.education.platform.common.enums.SmsTypeEnum;
import com.education.platform.api.service.common.Validservice;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.service.entity.PageDTO;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.common.util.ValidatorUtils;

import com.education.platform.dao.entity.*;
import com.education.platform.dao.model.CourseCommentModel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
* describe: 通用功能
* @author : tomato
* @date: 2020-06-07 11:38:44.106
**/
@RestController
@Api("通用功能")
@RequestMapping("common")
@Validated
public class CommonController {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);
    
	@Autowired
    private Validservice validservice;
	@Autowired
    private CourseService courseService;
	@Autowired
    private ArticleService articleService;
	@Autowired
    private GoodsService goodsService;

    @Autowired
    private CacheDataService cacheDataService;

    @Autowired
    private CourseCommentService courseCommentService;


    /**
     * 发送短信验证码
     * @param sendSmsVO
     * @return
     */
    @ApiOperation(value = "发送短信验证码",notes="发送短信验证码")
    @RequestMapping(value = "/sendSms", method = RequestMethod.POST)
    public void sendSms(@RequestBody SendSmsVO sendSmsVO) {
        //校验手机号参数是否正确
        ValidatorUtils.isMobile(sendSmsVO.getCellphone());
        Integer type = sendSmsVO.getType()==null?SmsTypeEnum.LOGIN_CODE.getValue():sendSmsVO.getType();
        if(SmsTypeEnum.LOGIN_CODE.getValue()!=type&&SmsTypeEnum.BINDING_CODE.getValue()!=type){
            sendSmsVO.setType(SmsTypeEnum.LOGIN_CODE.getValue());
        }
        //发送验证码
         validservice.sendMessageCode(sendSmsVO.getCellphone(), type);
    }




    /**
     * 主页搜索   课程，文章，商品
     * @param keyword
     * @return
     */
    @ApiOperation(value = "主页搜索",notes="主页搜索")
    @GetMapping(value = "/queryAll")
    public List<QueryAllResponseVO> queryAll(@RequestParam String keyword) {
        if(StringUtils.isEmpty(keyword)){
            throw new BusinessException("请输入关键词");
        }
        List<QueryAllResponseVO> responseVOList = new ArrayList<>();
        QueryAllResponseVO responseVO;
        //课程
        CourseDO courseQuery = new CourseDO();
        courseQuery.setCourseName(keyword);
        List<CourseDO> courseDOS = courseService.getList(courseQuery);
        if(CollectionUtils.isNotEmpty(courseDOS)){
            for(CourseDO courseDO:courseDOS){
                responseVO = new QueryAllResponseVO();
                responseVO.setId(courseDO.getId());
                responseVO.setTitle(courseDO.getCourseName());
                responseVO.setTypeName("课程");
                responseVO.setTypeCode("course");
                responseVOList.add(responseVO);
            }
        }
        //文章
        ArticleDO articleQuery = new ArticleDO();
        articleQuery.setTitle(keyword);
        List<ArticleDO> articleDOS = articleService.getList(articleQuery);
        if(CollectionUtils.isNotEmpty(articleDOS)){
            for(ArticleDO articleDO:articleDOS){
                responseVO = new QueryAllResponseVO();
                responseVO.setId(articleDO.getId());
                responseVO.setTitle(articleDO.getTitle());
                responseVO.setTypeName("文章");
                responseVO.setTypeCode("article");
                responseVOList.add(responseVO);
            }
        }
        //商品
        GoodsDO goodsQuery = new GoodsDO();
        goodsQuery.setGoodsName(keyword);
        List<GoodsDO> goodsDOS = goodsService.getList(goodsQuery);
        if(CollectionUtils.isNotEmpty(goodsDOS)){
            for(GoodsDO goodsDO:goodsDOS){
                responseVO = new QueryAllResponseVO();
                responseVO.setId(goodsDO.getId());
                responseVO.setTitle(goodsDO.getGoodsName());
                responseVO.setTypeName("商品");
                responseVO.setTypeCode("goods");
                responseVOList.add(responseVO);
            }
        }

        //保存搜索词。
        cacheDataService.saveQueryKeyWord(keyword);
        return responseVOList;
    }



    /**
     * 点赞
     * @param
     *
     */
    @ApiOperation(value = "点赞")
    @PostMapping("like")
    public Boolean like(@RequestBody @Valid LikeUpdateVO updateVO) {
        if(updateVO.getTopicType()!=0&&updateVO.getTopicType()!=1){
            throw new BusinessException("未知类型");
        }
        cacheDataService.likeOperate(updateVO.getTopicId(),updateVO.getStatus(),updateVO.getTopicType());
        return true;
    }


    /**
     * 收藏
     * @param collectionUpdateVO 收藏
     *
     */
    @ApiOperation(value = "收藏")
    @PostMapping("collection")
    public Boolean collection(@RequestBody @Valid CollectionUpdateVO collectionUpdateVO) {
        if(collectionUpdateVO.getTopicType()!=0&&collectionUpdateVO.getTopicType()!=1){
            throw new BusinessException("未知类型");
        }
        cacheDataService.collectOperate(collectionUpdateVO.getTopicId(),collectionUpdateVO.getStatus(),collectionUpdateVO.getTopicType());
        return true;
    }



    /**
     * 查询课程评论列表
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询评论列表")
    @PostMapping("getComments")
    public CourseCommentPageInfoVO getComments(@RequestBody @Valid CourseCommentQueryVO queryVO) {


        CourseCommentModel queryDO = BeanUtil.convert(queryVO, CourseCommentModel.class);
        queryDO.setAuditStatus(AuditTypeEnum.AUDIT.getValue());
        if(ThreadUser.getUserTokenRedisKey()!=null){
            queryDO.setUserId(ThreadUser.getUserId());
        }
        Page<CourseCommentResponseVO> page = PageHelper.startPage(queryVO.getPageNum(),100);
        List<CourseCommentModel> courseCommentDTOS = courseCommentService.getAuditComment(queryDO);
        CourseCommentPageInfoVO pageInfoVO = new CourseCommentPageInfoVO();
        BeanUtils.copyProperties(page.toPageInfo(), pageInfoVO);
        List<CourseCommentResponseVO> voList = BeanUtil.convert(courseCommentDTOS, CourseCommentResponseVO.class);
        voList.parallelStream().forEach(vo->{
            if(ValidatorUtils.mobile(vo.getUserName())){
                vo.setUserName(vo.getUserName().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
            }
        });
        pageInfoVO.setList(voList);
        return pageInfoVO;
    }

    /**
     * 提交课程评论
     *
     * @param
     * @return
     */
    @ApiOperation(value = "提交评论")
    @PostMapping("commitBack")
    public Boolean commitBack(@RequestBody @Valid CourseCommentUpdateVO updateVO) {
        CourseCommentDO commentDTO = BeanUtil.convert(updateVO, CourseCommentDO.class);
        courseCommentService.commitComment(commentDTO);
        return Boolean.TRUE;
    }



    /**
     *  查询点赞列表
     * @param
     * @return 分页参数
     */
    @ApiOperation(value = " 查询点赞列表")
    @PostMapping("getLikeList")
    public PageDTO<CollectOrLikeListResponseVO> getLikeList(@RequestBody @Valid CollectionOrLikeRequestVO requestVO) {
        return cacheDataService.getUserCollectionOrLikeList(RedisCountTypeEnum.LIKE.getValue(),
                requestVO.getTopicType(),requestVO.getPageNum(),requestVO.getPageSize());
    }
    /**
     *  查询点赞列表
     * @param
     * @return 分页参数
     */
    @ApiOperation(value = " 查询收藏列表")
    @PostMapping("getCollectionList")
    public PageDTO<CollectOrLikeListResponseVO> getCollectionList(@RequestBody @Valid CollectionOrLikeRequestVO requestVO) {
        return cacheDataService.getUserCollectionOrLikeList(RedisCountTypeEnum.COLLECTION.getValue(),
                requestVO.getTopicType(),requestVO.getPageNum(),requestVO.getPageSize());
    }



    /**
     * 主热门搜索
     * @param
     * @return
     */
    @ApiOperation(value = "获取热门搜索词",notes="获取热门搜索词")
    @GetMapping(value = "/getHotSearch")
    public List<String> getHotSearch( ) {
     return   cacheDataService.getQueryKeyWordList(10);

    }



}
